﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ecodex.RestAPI;
using Ecodex.RestAPI.Exceptions;

namespace EcodexIntegrationSample.Controllers
{
    class frmObtenerTokenyHoraController
    {
        private View.IfrmObtenerTokenyHora _view;

        public frmObtenerTokenyHoraController(View.IfrmObtenerTokenyHora view)
        {
            _view = view;
            _view.onObtenerToken += _view_onObtenerToken;
        }

        void _view_onObtenerToken(object sender, EventArgs e)
        {
            try
            {
                Utils.Utilerias util = new Utils.Utilerias();
                Uri uri = new Uri(util.urlApi);
                RestApi api = new RestApi(uri);
                var resultado = api.GetToken(_view.RFCEmisor, util.INTEGRATOR_ID);
                _view.Token = resultado.access_token;
                _view.FechaHora = resultado.service_datetime.ToString();
            }
            catch (FallaAplicacion ex)
            {
                using (var errorForm = new Forms.Error(TranslateErrorAPI.ToServiceError(_view.RFCEmisor, ex)))
                {
                    errorForm.ShowDialog();
                }
            }
            catch (FallaSesion fallaSession)
            {
                _view.ShowSessionError(TranslateErrorAPI.ToSessionError(_view.RFCEmisor, fallaSession));
            }
            catch (FallaValidacion fallaValidacion)
            {
                using (var errorForm = new Forms.Error(TranslateErrorAPI.ToServiceError(_view.RFCEmisor, fallaValidacion)))
                {
                    errorForm.ShowDialog();
                }
            }
        }
    }
}
